<?php

/**
 * +----------------------------------------------------------------------
 * | TickyPHP [ This is a freeware ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2015 All rights reserved.
 * +----------------------------------------------------------------------
 * | Author: 罗敏贵 <e-mail:minguiluo@163.com> <QQ:271391233>
 * +----------------------------------------------------------------------
 * | SVN: $Id: Newsclass.php 09594 2018-09-04 09:29:53 luomingui $
 * +----------------------------------------------------------------------
 * | 文件功能：对应的表名:tky_newsclass
 * +----------------------------------------------------------------------
 */

namespace application\admin\controller;

use ticky\request;
use ticky\tree;

class category extends base {

    //首页
    public function index() {
        $modelarr = getsitemodel();

        $tree = new tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $data = db('category')->where(['siteid' => $this->siteid])->order('sort ASC,catid ASC')->select();

        $array = array();
        foreach ($data as $v) {
            $modelid = $v['modelid'];
            $type = $v['type'];
            $catid = $v['catid'];
            $parentid = $v['parentid'];
            $catname = $v['catname'];
            $pclink = $v['pclink'];
            if ($type == "0") {
                $v['catlink'] = '/admin/content/add/?action=add&modelid=' . $modelid . '&catid=' . $catid;
            } elseif ($type == "1") {
                $v['catlink'] = '/admin/category/page_content/?catid=' . $catid;
            } else {
                $v['catlink'] = $pclink . "'  target='_blank";
            }

            $addurl = '/admin/category/add/?action=add&modelid=' . $modelid . '&type=' . $type . '&catid=' . $catid . '&parentid=' . $parentid;
            $editurl = '/admin/category/update/?action=edit&type=' . $type . '&catid=' . $catid . '&parentid=' . $parentid;
            $delurl = '/admin/category/delete/?action=del&type=' . $type . '&id=' . $catid . '&parentid=' . $parentid;
            $v['id'] = $catid;
            $v['name'] = $catname;
            $v['cattype'] = $type == "0" ? '内部栏目' : ($type == "1" ? '<span style="color:green">单页面</span>' : '<span style="color:red">外部链接</span>');
            $v['catmodel'] = $modelid ? $modelarr[$modelid] : '';

            $v['disabled'] = $v['disabled'] == '1' ? '<span style="color:red">是</span>' : '否';
            $v['member_publish'] = $v['member_publish'] ? '<span style="color:red">是</span>' : '否';

            $v['string'] = '<a  href="' . $addurl . '" class="btn btn-primary btn-xs" >' . L('category_subclass') . '</a>
			<a href="' . $editurl . '" class="btn btn-success btn-xs">' . L('edit') . '</a>
			<a href="' . $delurl . '"  class="btn btn-warning btn-xs" >' . L('delete') . '</a>';
            $array[] = $v;
        }

        $str = "<tr class='text-c'>
                    <td><input type='text' class='input-text listorder' name='sort[]' value='\$sort' style='width: 50px;'><input type='hidden' name='id[]' value='\$id'></td>
                    <td>\$id</td>
                    <td class='text-l'>\$spacer<a href='\$catlink'>\$name</a></td>
                    <td>\$cattype</td>
                    <td>\$catmodel</td>
                    <td>\$disabled</td>
                    <td>\$member_publish</td>
                    <td class='td-manage'>\$string</td>
                </tr>";

        $tree->init($array);
        $categorys = $tree->get_tree(0, $str);
        //debug($categorys);
        $this->assign('items', $categorys);
        $this->display('category/index');
    }

    /**
     * 排序栏目
     */
    public function sort() {
        if (isset($_POST["dosubmit"])) {
            foreach ($_POST['id'] as $key => $val) {
                db('category')->update(array('sort' => $_POST['sort'][$key]), ['catid' => intval($val)]);
            }
            showmsg('排序栏目成功');
        }
    }

    //实现无限级树型（函数递归算法）
    private function getTree($data, $pid) {
        $tree = '';
        foreach ($data as $k => $v) {
            if ($v['parentid'] == $pid) { //父亲找到儿子
                $v['children'] = $this->getTree($data, $v['catid']);
                $tree[] = $v;
                //unset($data[$k]);
            }
        }
        return $tree;
    }

    // 添加记录
    public function add() {
        load_extend('form.class.php');
        if (request::isPost()) {
            $type = request::get('type', 0);
            if ($type != 2) {   //非外部链接
                $res = db('category')->where(array('catdir' => $_POST['catdir']))->find();
                if ($res) {
                    showmsg('栏目目录已存在');
                }
            }
            $data = $this->post_frm();
            $catid = db('category')->insert($data);
            if ($type != 2) {   //非外部链接
                if ($type == 1) {   //单页类型
                    $arr = array();
                    $arr['catid'] = $catid;
                    $arr['title'] = request::post('catname', '');
                    $arr['catdir'] = request::post('catdir', '');
                    $arr['keywords'] = request::post('seo_keywords', '');
                    $arr['description'] = request::post('seo_description', '');
                    $arr['updatetime'] = TIMESTAMP;
                    db('page')->insert($arr);
                    db('category')->where(array('catid' => $catid))->update(array('list_template' => '', 'show_template' => ''));
                }
                //如果系统设置是伪静态模式
                if (get_config('url_rule')) {
                    $_POST['pclink'] = URL_MODEL == 1 ? SITE_URL . 'index.php?s=/' . $_POST['catdir'] . '/' : SITE_URL . $_POST['catdir'] . '/';
                } else {
                    $_POST['pclink'] = 'home/index/lists/?catid=' . $catid;
                }
            }
            db('category')->where(array('catid' => $catid))->update(array('arrchildid' => $catid, 'pclink' => $_POST['pclink']));  //更新本类的子分类及更新URL
            if ($_POST['parentid'] != '0') {
                $this->repairs($_POST['arrparentid']);
            }
            showmsg('添加栏目成功');
        } else {
            $action = request::get('action', 'add');
            $item['modelid'] = request::get('modelid', 0);
            $item['type'] = request::get('type', 0);
            $item['parentid'] = request::get('parentid', 0);
            $item['catid'] = request::get('catid', 0);

            $item['member_publish'] = 0;
            $item['disabled'] = 0;
            $item['openpl'] = 0;
            $item['closed'] = 0;
            $item["parentid"] = request::get('catid', 0);
            $this->assign('postUrl', '/admin/category/add');
            $this->assign('action', '添加');
            $this->assign('item', $item);
            if ($item['type'] == 2) {
                $title = "外部链接";
            } else if ($item['type'] == 1) {
                $title = "单页面";
            } else {
                $title = "内部栏目";
            }
            $this->assign('title', $title);
            //debug($item);
            $this->display('category/manage');
        }
    }

    // 更新记录
    public function update() {
        load_extend('form.class.php');
        if (request::isPost()) {
            $data = $this->post_frm();
            $id = request::post('catid', 0);
            db('category')->where(['catid' => $id])->update($data);
            showmsg('修改栏目成功', '/admin/category');
        } else {
            $action = request::get('action', 'add');
            $item['modelid'] = request::get('modelid', 0);
            $item['type'] = request::get('type', 0);
            $item['parentid'] = request::get('parentid', 0);
            $item['catid'] = request::get('catid', 0);

            $item = db('category')->where(['catid' => $item['catid']])->find();
            $item['member_publish'] = $item['member_publish'] ? 0 : $item['member_publish'];
            $item['openpl'] = $item['openpl'] ? 0 : $item['openpl'];
            $item['closed'] = $item['closed'] ? 0 : $item['closed'];
            $this->assign('postUrl', '/admin/category/update');
            $this->assign('action', '修改');
            $this->assign('item', $item);
            if ($item['type'] == 2) {
                $title = "外部链接";
            } else if ($item['type'] == 1) {
                $title = "单页面";
            } else {
                $title = "内部栏目";
            }
            $this->assign('title', $title);
            //debug($item);
            $this->display('category/manage');
        }
    }

    // 删除记录
    public function delete() {
        $id = request::get('id', 0);
        $type = request::get('type', 0);
        $data = db('category')->field('arrparentid,arrchildid')->where(array('catid' => $id))->find();
        if (strpos($data['arrchildid'], ',')) {
            showmsg('分类删除失败：该分类下有子分类！');
        }
        $ret = db('category')->delete(array('catid' => $id));
        if ($ret) {
            if ($type == 1) {
                db('page')->delete(array('catid' => $id));    //删除单页数据
            }
            $this->repairs($data['arrparentid']);
            delcache('categoryinfo');
            delcache('mapping');
            showmsg('分类删除成功！', '/admin/category');
        } else {
            showmsg('分类删除失败！', '/admin/category');
        }
    }

    //表单数据
    private function post_frm() {
        $arr = array();
        $arr['siteid'] = $this->siteid;
        $arr['modelid'] = request::post('modelid', '');
        $arr['parentid'] = request::post('parentid', '');
        $arr['arrparentid'] = request::post('arrparentid', '');
        $arr['arrchildid'] = request::post('arrchildid', '');
        $arr['catname'] = request::post('catname', '');
        $arr['subtitle'] = request::post('subtitle', '');
        $arr['sort'] = request::post('sort', '');
        $arr['type'] = request::post('type', '');
        $arr['pclink'] = request::post('pclink', '');
        $arr['member_publish'] = request::post('member_publish', '');
        $arr['disabled'] = request::post('disabled', '');
        $arr['catdir'] = request::post('catdir', '');
        $arr['catimg'] = request::post('catimg', '');
        $arr['category_template'] = request::post('category_template', '');
        $arr['list_template'] = request::post('list_template', '');
        $arr['show_template'] = request::post('show_template', '');
        $arr['seo_title'] = request::post('seo_title', '');
        $arr['seo_keywords'] = request::post('seo_keywords', '');
        $arr['seo_description'] = request::post('seo_description', '');

        if ($_POST['parentid'] == '0') {
            $_POST['arrparentid'] = '0';
        } else {
            $data = db('category')->field('arrparentid,arrchildid')->where(array('catid' => $_POST['parentid']))->find();
            $arr['arrparentid'] = $data["arrparentid"] . ',' . $_POST['parentid'];
        }

        return $arr;
    }

    /**
     * 批量修复栏目数据
     */
    private function repairs($arrparentid, $cpath = null) {
        $data1 = explode(',', $arrparentid);
        $data2 = $cpath ? explode(',', $cpath) : array();
        $data = array_merge($data1, $data2);
        foreach ($data as $val) {
            if ($val) {
                $this->repair($val);
            }
        }
    }

    /**
     * 修复栏目数据
     */
    private function repair($catid) {
        db('category')->where(array('catid' => $catid))->update(array('arrchildid' => $this->get_arrchildid($catid)));  //更新本类的子分类
    }

    /**
     *
     * 获取子栏目ID列表
     * @param $catid 栏目ID
     */
    private function get_arrchildid($catid) {
        $arrchildid = $catid;
        $data = db('category')->field('catid')->where("FIND_IN_SET('$catid',arrparentid)")->order('catid ASC')->select();
        foreach ($data as $val) {
            $arrchildid .= ',' . $val['catid'];
        }
        return $arrchildid;
    }

    /**
     * 单页内容
     */
    public function page_content() {
        $catid = request::get('catid', 0);
        if (request::isPost()) {
            $arr = array();
            $arr['title'] = request::post('title', '');
            $arr['catdir'] = request::post('catdir', '');
            $arr['keywords'] = request::post('keywords', '');
            $arr['description'] = request::post('description', '');
            $arr['content'] = request::post('content', '');
            $arr['updatetime'] = TIMESTAMP;
            db('page')->where(['catid' => $catid])->update($arr);
            showmsg('单页内容更新成功！');
        } else {
            $item = db('page')->where(['catid' => $catid])->find();
            $this->assign('title', '修改单页面');
            $this->assign('item', $item);
            $this->display('category/page_content');
        }
    }

}
